package demo.demo07.test03;

//死锁，多个线程互相抱着对方需要的资源，互相僵持不下
public class Deadlock {
    public static void main(String[] args) {
        Makeup g1 = new Makeup(0, "灰姑娘");
        Makeup g2 = new Makeup(1, "皇后");
        g1.start();
        g2.start();
    }
}

//
class Lipstick {

}

class Mirror {

}

class Makeup extends Thread {
    //需要的资源只有一份，用static来修饰
    static Mirror mirror = new Mirror();
    static Lipstick lipstick = new Lipstick();

    int Choice;
    String GirlName;

    Makeup(int Choice, String GirlName) {
        this.Choice = Choice;
        this.GirlName = GirlName;
    }

    @Override
    public void run() {
        Makeup();
    }

    //互相持有对方的锁，就是拿到对方的资源
    private void Makeup() {
        if (Choice == 0) {
            synchronized (lipstick) {
                System.out.println(this.GirlName + "获得口红锁");

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            synchronized (mirror) {//一秒后获得镜子
                System.out.println(this.GirlName + "获得镜子锁");
            }
        } else {
            synchronized (mirror) {
                System.out.println(this.GirlName + "获得镜子锁");

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            synchronized (lipstick) {//一秒后获得镜子
                System.out.println(this.GirlName + "获得口红锁");
            }
        }
    }
}